<template>
    <div class="app-container" v-if="canList">
        <div class="filter-container">
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                      placeholder="用户名"
                      v-model="listQuery.username">
            </el-input>
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                      placeholder="店铺名"
                      v-model="listQuery.shopName">
            </el-input>
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                      placeholder="手机号"
                      v-model="listQuery.mobile">
            </el-input>
            <el-select @change='handleFilter' clearable class="filter-item" style="width: 130px"
                       v-model="listQuery.status"
                       placeholder="状态">
                <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item" :value="index">
                </el-option>
            </el-select>
            <!--            <el-date-picker-->
            <!--                    v-model="listQuery.createTime"-->
            <!--                    type="datetimerange"-->
            <!--                    range-separator="至"-->
            <!--                    start-placeholder="创建时间开始日期"-->
            <!--                    end-placeholder="创建时间结束日期">-->
            <!--            </el-date-picker>-->

            <el-button class="filter-item" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-search"
                       @click="handleFilter">查找
            </el-button>
<!--            <el-button class="filter-item" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-search"-->
<!--                       @click="handleFilter">查找-->
            </el-button>
            <el-button class="filter-item" @click="handleCreate" type="primary"
                       v-if="canSave" icon="el-icon-edit">添加
            </el-button>
            <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"
                       @click="handleDownload">导出
            </el-button>
        </div>

        <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
                  style="width: 100%;min-height:1000px;">
            <el-table-column align="center" label="序号">
                <template slot-scope="scope">
                    <span>{{scope.row.userId}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="用户名">
                <template slot-scope="scope">
                    <span>{{scope.row.username}}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column align="center" label="密码">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.password}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column align="center" label="邮箱">
                <template slot-scope="scope">
                    <span>{{scope.row.email}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="用户编号">
                <template slot-scope="scope">
                    <span>{{scope.row.userCode}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="店铺名">
                <template slot-scope="scope">
                    <span>{{scope.row.shopName?scope.row.shopName:getShopName}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="手机号">
                <template slot-scope="scope">
                    <span>{{scope.row.mobile}}</span>
                </template>
            </el-table-column>


            <!--            <el-table-column align="center" label="创建者ID">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.createUserId}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column align="center" label="部门ID">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.deptId}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column align="center" label="状态">
                <template slot-scope="scope">
                    <span>{{statusOptions[scope.row.status]}}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column align="center" label="创建时间">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.createTime}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->

            <el-table-column align="center" label="创建时间">
                <template slot-scope="scope">
                    <span>{{parseTime(scope.row.createTime)}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope.row)">编辑
                    </el-button>
                    <el-button v-if="canSave" size="mini" type="danger"
                               @click="handleDelete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px"
                     style='width: 400px; margin-left:50px;'>
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="temp.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="name">
                    <el-input placeholder="如果增加/修改密码请输入否则不填" v-model="temp.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="name">
                    <el-input v-model="temp.email"></el-input>
                </el-form-item>
                <el-form-item label="绑定用户编号" prop="name">
                    <el-input v-model="temp.userCode"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="name">
                    <el-input v-model="temp.mobile"></el-input>
                </el-form-item>
                <!--                <el-form-item label="创建者ID" prop="name">-->
                <!--                    <el-input v-model="temp.createUserId"></el-input>-->
                <!--                </el-form-item>-->
                <el-form-item label="角色" prop="roleIdList" v-if="roleList">

                    <el-checkbox-group v-model="temp.roleIdList">
                        <el-checkbox  v-for="(role,index) in roleList" :key="index" :label="role.roleId">
                            {{role.roleName}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select class="filter-item" v-model="temp.status" placeholder="状态">
                        <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item"
                                   :value="index">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间" prop="date">
                    <el-date-picker v-model="temp.createTime" type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="创建时间">
                    </el-date-picker>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForm">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
                <el-button v-else type="primary" @click="updateData">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        padding-bottom: 20px;
    }
</style>

<script>
    import {list, save, update, remove, getRoles,info} from '@/api/sys_user'
    import waves from '@/directive/waves' // 水波纹指令
    import {parseTime} from '@/utils'


    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'

    export default {
        name: 'test',
        directives: {
            waves
        },
        data() {
            return {
                roleList:null,
                roleIdList:[],
                statusOptions: ['禁用', '正常'],
                tableKey: 0,
                list: null,
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    limit: 20,
                    sidx: 'user_id',
                    order: 'desc'
                    ,
                    username: null
                    ,
                    password: null
                    ,
                    email: null
                    ,
                    mobile: null
                    ,
                    createUserId: null
                    ,
                    deptId: null
                    ,
                    createTime: null
                    ,
                    status: null,
                    shopName:null
                },
                temp:
                    {
                        roleIdList: [],
                        userId: null,
                        username: null,
                        password: null,
                        email: null,
                        mobile: null,
                        status: null,
                        createUserId: null,
                        createTime: null,
                        deptId: null,
                        userCode:null,
                        shopName:null
                    }
                ,
                dialogFormVisible: false,
                dialogStatus:
                    '',
                textMap:
                    {
                        update: '修改',
                        create:
                            '新增'
                    }
                ,
                rules:
                    {
                        username: [
                            {
                                required: true, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        password: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        email: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        mobile: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        status: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'blur'
                            }
                        ]
                        ,
                        createUserId: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        createTime: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        deptId: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                    }
                ,
                downloadLoading: false,
                qData:
                    {
                        token: '',
                        key:
                            ''
                    }
            }
        },
        created() {
            this.getList()

        },
        computed: {
            getShopName(){
                return process.env.VUE_APP_SHOPNAME;
            },
            ...mapGetters([
                'perms'
            ]),
            canSave() {
                return hasAuth(this.perms, 'sys:user:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'sys:user:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'sys:user:update')
            },
            canList() {
                return hasAuth(this.perms, 'sys:user:list')
            }
        },
        methods: {
            parseTime(time) {
                return parseTime(time,'{y}-{m}-{d}')
            },
            getList() {
                this.listLoading = true

                // 如果存在时间
                if (this.listQuery.createTime) {
                    this.listQuery['createTimeStart'] = parseTime(this.listQuery.createTime[0])
                    this.listQuery['createTimeEnd'] = parseTime(this.listQuery.createTime[1])
                } else {
                    this.listQuery['createTimeStart'] = null
                    this.listQuery['createTimeEnd'] = null
                }
                list(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                })

                getRoles().then(res => {
                    this.roleList = res.data

                })
            },

            handleFilter() {
                this.listQuery.page = 1
                console.log(this.listQuery.order)
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片


            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
            },
            resetTemp(row) {


                // if (row) {
                //     this.temp = Object.assign({}, row) // copy obj
                // }
                // if(!this.temp.roleIdList){
                //     this.temp.roleIdList = []
                // }
                if(row){
                    info(row.userId).then( res =>{
                        this.temp  = res.data
                        this.temp.password = null
                        // console.log(this.temp)
                    })
                }else {
                    this.temp = {roleIdList:[]}
                    // this.temp.roleIdList = []
                }

            },
            handleCreate() {
                this.beforeFormShow()
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(row) {
                this.beforeFormShow(row)
                this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData([row.userId])
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData(ids) {
               // const ids = [this.temp.userId]
                console.log(ids)
                if (process.env.VUE_APP_SHOPNAME == '五集时代'){
                    remove(ids).then(res => {
                        // 从当前队列中移除
                        for (const v of this.list
                            ) {
                            if (v.userId === this.temp.userId) {
                                const index = this.list.indexOf(v)
                                this.list.splice(index, 1)
                                break
                            }
                        }
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        })
                    })
                }else {
                    remove({ids:ids}).then(res => {
                        // 从当前队列中移除
                        for (const v of this.list
                            ) {
                            if (v.userId === this.temp.userId) {
                                const index = this.list.indexOf(v)
                                this.list.splice(index, 1)
                                break
                            }
                        }
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        })
                    })
                }

            },
            handleUpdate(row) {
                this.beforeFormShow(row)
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            console.log(this.temp)
                            update(this.temp).then(() => {
                                for (const v of this.list
                                    ) {
                                    if (v.userId === this.temp.userId) {
                                        const index = this.list.indexOf(v)
                                        this.list.splice(index, 1, this.temp)
                                        break
                                    }
                                }
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                this.dialogFormVisible = false
            },
            handleDownload() {
                this.downloadLoading = true
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = [
                        '序号'
                        ,
                        '用户名'
                        ,
                        '密码'
                        ,
                        '邮箱'
                        ,
                        '手机号'
                        ,
                        '创建者ID'
                        ,
                        '部门ID'
                        ,
                        '状态'
                        ,
                        '创建时间'
                    ]
                    const filterVal = ['id'
                        , 'username'
                        , 'password'
                        , 'email'
                        , 'mobile'
                        , 'createUserId'
                        , 'deptId'
                        ,
                        'status'
                        ,
                        'createTime'
                    ]
                    const data = this.formatJson(filterVal, this.list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'table-list'
                    })
                    this.downloadLoading = false
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                        return v[j]
                    }
                ))
            },
        }
    }
</script>
